package com.lanou.bookstore.user.dao;

import com.lanou.Util.JDBCUtil;
import com.lanou.bookstore.user.domain.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class LoginDao {
    public User login(String username, String password) {
        try {
            User user = new User();
            Connection conn = JDBCUtil.getConn();
            //查询数据库
            String sql = "select * from tb_user where username=? and password=?";
            PreparedStatement statement = conn.prepareStatement(sql);
            statement.setString(1, username);
            statement.setString(2, password);
            ResultSet rs = statement.executeQuery();
            rs.next();
            user.setUsername(username)
                    .setPassword(password);
            rs.close();
            statement.close();
            conn.close();
            return user;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    //能否登录成功
    public boolean canLogin(String username, String password) {
        Connection conn = JDBCUtil.getConn();
        String sql = "select count(*) from tb_user where " +
                "username=? and password=?";
        try {
            PreparedStatement statement
                    = conn.prepareStatement(sql);//预编译sql 生成一个预编译的statement对象
            statement.setString(1, username);
            statement.setString(2, password);
            ResultSet rs = statement.executeQuery();
            boolean canLogin = false;
            if (rs.next()) {
                int count = rs.getInt(1);
                canLogin = count > 0;
            }
            statement.close();
            rs.close();
            conn.close();
            return canLogin;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }
}

